gitPath='/home/apps_admin/sources/workflow';
buildsPath='/home/apps_admin/workflow_builds';

cd $gitPath;

port=7000;
branch='Release';
env='Development';

case "${1,,}" in
  sign) branch='ESign'; port=7002;;
  jan) branch='2022_Jan'; port=7001;;
  feb) branch='2022_Feb'; port=7001;;
  mar) branch='2022_Mar'; port=7001;;
  apr) branch='2022_Apr'; port=7001;;
  may) branch='2022_May'; port=7001;;
  aug) branch='2022_Aug'; port=7001;;
  sep) branch='2021_Sep'; port=7001;;
  oct) branch='2021_Oct'; port=7001;;
  nov) branch='2021_Nov'; port=7001;;
  dec) branch='2021_Dec'; port=7001;;
  core) branch='2022_Feb_WFApiCore'; port=8200;;
  --q) branch='Release'; port=6001; env='Simulation';;
  *) branch='Release'; port=7000;;
esac

if [ -n "${2,,}" ]; then
  case "${2,,}" in
    --r)
      port=7000;;

    --q)
      port=7002;
      env='Simulation';;
  
    --q1)
      port=7003;
      env='Simulation1';;
  esac
fi

# git switch branch and pull codes.
git checkout -- * &> /dev/null;

if git checkout $branch &> /dev/null; then
  echo "  switch to branch:${branch}...";
  git checkout -b $branch origin/$branch &> /dev/null;
  echo '  branch switch completed!';
fi

echo '  git pull...';
git pull;
echo '  git pull completed!';

# netcore publish
echo '  app build&publish...';
rm -rf $buildsPath/* &> /dev/null;
cd $gitPath/Src/src/IWorkFlow.Web;
source /etc/profile;
dotnet publish -c release -o $buildsPath 1> /dev/null;
if [ $? -ne 0 ]; then
  echo "  app build&publish error, please retry!";

  exit 1;
fi

chmod 777 -R $buildsPath;
echo '  app build&publish completed!';

# docker builder and start app.
cd $buildsPath;

echo '  remove docker app and image...';
docker rm -f `docker ps -a | grep $port | awk {'print $1'}` &> /dev/null;
docker rmi -f iworkflow_${branch,,}_$port &> /dev/null;
echo '  remove docker app and image completed!';

echo '  build docker image...';
docker build -t iworkflow_${branch,,}_$port . &> /dev/null;

if [ $? -ne 0 ]; then
  echo "  docker image build error, please retry!";

  exit 1;
fi

echo '  build docker image completed!';
echo "  docker app is runing: iworkflow_${branch,,}_$port";
docker run -e "ASPNETCORE_ENVIRONMENT=${env}" --restart=always --name=iworkflow_${branch,,}_$port -p $port:80 -v /home/apps_admin/logs/tingyun:/var/log/tingyun -v /mnt/iWorkflowUploadFiles:/app/staticfiles -d iworkflow_${branch,,}_$port &> /dev/null;

if [ $? -eq 0 ]; then
  echo "update success, please visit: http://10.164.2.213:${port}/";
fi
